from ril_api import API
import json
import commands
import re
import settings
import shutil

from datetime import datetime

pdf_re = re.compile('PDF (.+)\.pdf creado en (.+)')

urls = []
bajados = []
ril = API(settings.API_KEY)
s=json.loads(ril.get(settings.USER, settings.PASSWORD, state='unread'))
entries = s['list'] # esto es un dict
for e in entries.values():  # e es un dict
    if "youkioske" in e['url']:
        urls.append(e['url'])

for url in urls:
    pdf = url.strip("/")
    pdf = pdf[pdf.rfind("/")+1:]
    pdf = pdf.strip("-")
    
    print "%s: bajando %s" % (datetime.now(), url,)
    ( stat, output ) = commands.getstatusoutput( "java -jar jissuuDownloader.jar -d %s" % (url,) )
    if( stat == 0 ): 
        s=pdf_re.search(output)
        if s:
            shutil.move(s.group(2)+s.group(1)+'.pdf', pdf+'.pdf')
            ( stat, output ) = commands.getstatusoutput( "calibredb add %s" % (pdf+'.pdf' ))
            if( stat == 0 ):
                bajados.append(url)
                shutil.rmtree(s.group(2))
                shutil.os.unlink(pdf+ '.pdf')
            else:
                print "ERROR: Fallo al subir a calibre: %s" % output
        else:
            print "ERROR: %s ha fallado" % (pdf)
    else:
        print "ERROR: Ejecucion de jissuuDownloader ha fallado: %s" % output

bajados = [{"url":x} for x in bajados]
ril.send(settings.USER, settings.PASSWORD, read=bajados)  #marcamos como leidos los periodicos bajados OK   
                        
